﻿app.factory('LoginFactory', function ($http, $q) {
    var status = {}; // Check if the user is logged in - boolean

    // Talk to the local storage to set the status of Logged In
    if (localStorage.getItem('token')) {
        status.loggedin = true
    } else {
        status.loggedin = false
    };

    // Make the API call for login
    var login = function (user) {
        console.log("factorylogin try to login", user)
        var def = $q.defer();
        $http({
            method: 'POST',
            url: '/Token',
            data: 'username=' + user.username + '&password=' + user.password + '&grant_type=password',
            contentType: 'application/x-www-form-urlencoded'
        }).success(function (data) {
            localStorage.setItem('token', data.access_token);
            status.loggedin = true;
            def.resolve(data);
        }).error(function (data) {
            def.reject();
            logout();
        });
        return def.promise;
    }

    // Log the user out
    var logout = function () {
        localStorage.removeItem('token');
        status.loggedin = false;
    };

    // Get the user's info on login
    var getInfo = function () {
        var def = $q.defer();
        $http({
            method: 'GET',
            url: '/GetInfo',
            //headers: { Authorization: 'Bearer ' + localStorage.getItem('token') }
        }).success(function (data) {
            def.resolve(data);
        }).error(function (data) {
            def.reject(data);
        })
        return def.promise;
    }


    // Expose the methods
    return {
        factorylogin: login,
        logout: logout,
        getUserInfo: getInfo,
        status: status
    }
});